package com.autumn.annotations.leetcode.leet;

import redis.clients.jedis.Jedis;

/**
 * ClassName: Redis
 * Description:
 * Author: Shen_Yue
 * Date: 2023/11/30 23:22
 * History:
 * <author>          <time>          <version>          <desc>
 * Shen_Yue    2023/11/30 23:22   @Version 1.0        描述
 */
public class Redis {

    private static final String REDIS_KEY = "unique_code_counter";
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int CODE_LENGTH = 6;

    private static Jedis jedis = new Jedis("47.93.56.164", 6379);

    public static void main(String[] args) {
        // 生成唯一code
        String uniqueCode = generateCode();
        System.out.println("生成的唯一code: " + uniqueCode);
    }

    public static String generateCode() {
        long uniqueCode = jedis.incr(REDIS_KEY);
        return convertToCode(uniqueCode);
    }

    private static String convertToCode(long number) {
        StringBuilder codeBuilder = new StringBuilder();

        while (number > 0) {
            int remainder = (int) (number % CHARACTERS.length());
            codeBuilder.insert(0, CHARACTERS.charAt(remainder));
            number = number / CHARACTERS.length();
        }

        // 补齐到6位
        while (codeBuilder.length() < CODE_LENGTH) {
            codeBuilder.insert(0, CHARACTERS.charAt(0));
        }

        return codeBuilder.toString();
    }
}
